package parser;

import antlr.RecognitionException;
import java.util.*;

class Variable extends Expr {
    
    int name;
    FunctionScope2 scope;
    
    Variable(int name, FunctionScope2 scope) {
        this.name = name;
        this.scope = scope;
    }

    void write(ByteStream out) {
        Integer index = scope.getIndex(name);
        if (index != null) {
            out.write(Opcodes.LOAD_FRAME);
            out.write(index);   
        } else {
            out.write(Opcodes.LOAD_GLOBAL);
            out.writeShort(name);
        }
    }

    void delete(ByteStream out) throws RecognitionException {
        Integer index = scope.getIndex(name);
        if (index != null) {
            out.write(Opcodes.DELETE);
            out.write(index);
        } else {
            out.write(Opcodes.DELETE_GLOBAL);
            out.writeShort(name);     
        }
    }
    
    void writeLHS(ByteStream out) throws RecognitionException {
        Integer index = scope.getIndex(name);
        if (index != null) {
            out.write(Opcodes.STORE_FRAME);
            out.write(index);   
        } else {
            out.write(Opcodes.STORE_GLOBAL);
            out.writeShort(name);
        }
    }
    
    void lhs() {
        scope.bind(name);
    }

}
